﻿using System;
using System.Data.Common;
using System.Xml;
using Microsoft.Practices.EnterpriseLibrary.Data;
using Microsoft.Practices.EnterpriseLibrary.Data.Sql;
using Unis.Framework.Core.Exceptions;
using Unis.Framework.Core.Log;
using Unis.Framework.ORM.BaseDefiniens.Enums;
using Unis.ORM;
using Unis.ORM.Persistence;
using Unis.Framework.Core.Data;
using Unis.Framework.Core.Utility;

namespace Unis.Framework.ORM.Persistence
{
    public class DatabaseHelper
    {
        // Fields
        private static string CONNECTION_NODES_PATH = "/configuration/connectionStrings/add";



        static DatabaseHelper()
        {
            //if (String.IsNullOrEmpty(DatabaseConfigurationScope.ConfigurationDatabase))
            //{
            //    var manager = new DataSettingsManager();
            //    DatabaseConfigurationScope.ConfigurationDatabase = manager.LoadSettings().DataConnectionString;
            //}

        }


        // Methods
        public static Database CreateDatabase(OrmConnectionParams ormP = null)
        {
            Database database;
            try
            {

                DatabaseConfigurationScope.ConfigurationDatabase =ConfigurationManager.GetAppSetting("UnisDBConnStr");



                #region 此段代码适用于将数据库链接字符串配置到Web.config或App.config文件中
                database = string.IsNullOrEmpty(DatabaseConfigurationScope.ConfigurationDatabase)
                   ? DatabaseFactory.CreateDatabase()
                   : DatabaseFactory.CreateDatabase(DatabaseConfigurationScope.ConfigurationDatabase);
                 //database = new SqlDatabase("Server=127.0.0.1;User Id=sa;Password=11;Database=UnisYLX");
                #endregion
            }
            catch (Exception exception)
            {
                string str = string.IsNullOrEmpty(DatabaseConfigurationScope.ConfigurationDatabase)
                    ? "DefaultDatabase"
                    : DatabaseConfigurationScope.ConfigurationDatabase;
                DatabaseConfigurationScope.ConfigurationDatabase = "";
                throw new APPException(string.Format("创建数据库对象出错,请检查配置的 {0} 数据库连接字符串", str), APPMessageType.SysErrInfo,
                    exception);
            }
            return database;
        }

        public static Database CreateDatabase(string name)
        {
            Database database;
            try
            {
                database = DatabaseFactory.CreateDatabase(name);
            }
            catch (Exception exception)
            {
                throw new APPException(string.Format("创建数据库对象出错,请检查配置的 {0} 数据库连接字符串", name), APPMessageType.SysErrInfo, exception);
            }
            return database;
        }

        private static string GetConnectionString(OrmConnectionParams ormP)
        {
            string connectionString = "", databaseConfigName = "";

            if (ormP == null) return connectionString;
            databaseConfigName = !String.IsNullOrEmpty(ormP.DataBaseConfigName)
                ? ormP.DataBaseConfigName
                : "DynamicConnection";

            connectionString = System.Configuration.ConfigurationManager.ConnectionStrings[databaseConfigName].ConnectionString;
            if (databaseConfigName == "DynamicConnection")
                connectionString = connectionString.Replace("$Server$", ormP.Ip)
                                                   .Replace("$UserId$", ormP.UserId)
                                                   .Replace("$Password$", ormP.Password)
                                                   .Replace("$Database$", ormP.DatabaseName);

            return connectionString;
        }


        public static string GetConnectionString()
        {
            return getKeyValue(getDatabaseCfgName());
        }

        private static string getDatabaseCfgName()
        {
            if (!string.IsNullOrEmpty(DatabaseConfigurationScope.ConfigurationDatabase))
            {
                return DatabaseConfigurationScope.ConfigurationDatabase;
            }
            string xpath = "/configuration/dataConfiguration";
            XmlDocument document = new XmlDocument();
            string configurationFile = AppDomain.CurrentDomain.SetupInformation.ConfigurationFile;
            document.Load(configurationFile);
            XmlNode node = document.SelectSingleNode(xpath);
            if (node == null)
            {
                throw new APPException(string.Format("请检查配置文件{0} 是否已经配置dataConfiguration/defaultDatabase", configurationFile), APPMessageType.SysErrInfo);
            }
            return node.Attributes["defaultDatabase"].Value;
        }

        private static string getKeyValue(string keyName)
        {
            string xpath = CONNECTION_NODES_PATH;
            XmlDocument document = new XmlDocument();
            string configurationFile = AppDomain.CurrentDomain.SetupInformation.ConfigurationFile;
            try
            {
                document.Load(configurationFile);
            }
            catch (Exception exception)
            {
                throw new APPException(string.Format("加载配置文件{0}出错", configurationFile) + exception.Message, APPMessageType.SysErrInfo);
            }
            foreach (XmlNode node in document.SelectNodes(xpath))
            {
                if (string.Compare(node.Attributes["name"].Value, keyName, true) == 0)
                {
                    return node.Attributes["connectionString"].Value;
                }
            }
            return string.Empty;
        }

        public static void SaveConnectionString(string connectionString)
        {
            setKeyValue(getDatabaseCfgName(), connectionString);
        }

        private static void setKeyValue(string keyName, string keyValue)
        {
            string xpath = CONNECTION_NODES_PATH;
            XmlDocument document = new XmlDocument();
            string configurationFile = AppDomain.CurrentDomain.SetupInformation.ConfigurationFile;
            try
            {
                document.Load(configurationFile);
            }
            catch (Exception exception)
            {
                throw new APPException(string.Format("加载配置文件{0}出错", configurationFile) + exception.Message, APPMessageType.SysErrInfo);
            }
            XmlNodeList list = document.SelectNodes(xpath);
            bool flag = false;
            foreach (XmlNode node in list)
            {
                if (string.Compare(node.Attributes["name"].Value, keyName, true) == 0)
                {
                    node.Attributes["connectionString"].Value = keyValue;
                    flag = true;
                    break;
                }
            }
            if (!flag)
            {
                TraceEx.Write("没有配置键值，请以这样的方式(add name=XX providerName=XX connectionString=XX)在config文件中配置。", APPMessageType.SysErrInfo);
            }
            document.Save(configurationFile);
        }
    }
}
